using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace USBDrive
{
    public class USBDriveInfo
    {
        public String Caption;
        public String SerialNumber;
        public String DriverLetter;
    }

    public class USBDriveInfoCap
    {

        public static List<USBDriveInfo> enumerateConnectedDevices()
        {
            string[] diskArray;
            string driveNumber;
            string driveLetter;

            List<USBDriveInfo> list = new List<USBDriveInfo>();


            ManagementObjectSearcher searcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
            foreach (ManagementObject dm in searcher1.Get())
            {
                diskArray = null;
                driveLetter = getValueInQuotes(dm["Dependent"].ToString());
                diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(',');
                driveNumber = diskArray[0].Remove(0, 6).Trim();
                    /* This is where we get the drive serial */
                    ManagementObjectSearcher disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
                    foreach (ManagementObject disk in disks.Get())
                    {

                        if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB")
                        {
                            USBDriveInfo inf = new USBDriveInfo();
                            inf.Caption = disk["Caption"].ToString();
                            inf.SerialNumber = parseSerialFromDeviceID(disk["PNPDeviceID"].ToString());
                            inf.DriverLetter = driveLetter;
                            list.Add(inf);
                        }
                    }
            }
            if (list.Count > 0) return list;
            return null;
        }

        public static USBDriveInfo getSerialNumberFromDriveLetter(string driveLetter)
        {
            string _driveLetter = driveLetter.ToUpper();

            if (!_driveLetter.Contains(":"))
            {
                _driveLetter += ":";
            }

            return matchDriveLetterWithSerial(_driveLetter);
        }

        private static USBDriveInfo matchDriveLetterWithSerial(string _driveLetter)
        {

            string[] diskArray;
            string driveNumber;
            string driveLetter;


            ManagementObjectSearcher searcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
            foreach (ManagementObject dm in searcher1.Get())
            {
                diskArray = null;
                driveLetter = getValueInQuotes(dm["Dependent"].ToString());
                diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(',');
                driveNumber = diskArray[0].Remove(0, 6).Trim();
                if (driveLetter == _driveLetter)
                {
                    /* This is where we get the drive serial */
                    ManagementObjectSearcher disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
                    foreach (ManagementObject disk in disks.Get())
                    {

                        if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB")
                        {
                            USBDriveInfo inf = new USBDriveInfo();
                            inf.Caption = disk["Caption"].ToString();
                            inf.SerialNumber = parseSerialFromDeviceID(disk["PNPDeviceID"].ToString());
                            return inf;
                        }
                    }
                }
            }
            return null;
        }

        private static string parseSerialFromDeviceID(string deviceId)
        {
            string[] splitDeviceId = deviceId.Split('\\');
            string[] serialArray;
            string serial;
            int arrayLen = splitDeviceId.Length - 1;

            serialArray = splitDeviceId[arrayLen].Split('&');
            serial = serialArray[0];

            return serial;
        }

        private static string getValueInQuotes(string inValue)
        {
            string parsedValue = "";

            int posFoundStart = 0;
            int posFoundEnd = 0;

            posFoundStart = inValue.IndexOf("\"");
            posFoundEnd = inValue.IndexOf("\"", posFoundStart + 1);

            parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1);

            return parsedValue;
        }

    }
}
